<template>
  <div>
    <el-card shadow="always" v-loading="loading" element-loading-text="数据加载中..." element-loading-background="rgba(256, 256, 256, 0.8)">
      <div style="background-color: #FAFAFA">
        <div class="block">
          <span class="demonstration">hover 触发子菜单</span>
          <el-cascader v-model="value" :options="options" :props="props" style="width:240px;" :show-all-levels="false" @change="handleChange" clearable>
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </div>
        <el-button type="primary" plain @click="AddRow" size="small " icon="el-icon-circle-plus-outline" style="margin: 10px 0px 10px;">添加一行</el-button>
        <el-button type="danger" plain @click="DeleteTableDataFun" size="small " icon="el-icon-delete">删除</el-button>
        <el-button type="success" plain @click="SaveData" size="small " icon="el-icon-document-checked">保存</el-button>
        <!-- stripe 斑马纹表格 -->
        <!-- border 带边框表格 -->
        <!-- @selection-change 复选框选择事件 -->
        <!-- @row-dblclick 行上双击事件 -->
        <!-- show-summary 表底的合计 -->
        <el-table :data="tableDataSearch" @selection-change="SelectFun" @row-dblclick="RowDblclick" @row-click="RowClick" show-summary :summary-method="getSummaries" stripe border @header-click="HeaderClick">
          <el-table-column type="selection" align="center" width="60px"></el-table-column>
          <!-- type="index" 自动编号 序号 -->
          <el-table-column type="index" label="序号" align="center" width="60px"></el-table-column>
          <el-table-column label="地址" width="250px" show-overflow-tooltip>
            <template slot="header">
              <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
            </template>
            <template slot-scope="scope">
              <el-input v-show="doubleclick==scope.row.line" type="text" placeholder="请输入地址" v-model="scope.row.address" size="mini" prefix-icon="el-icon-edit" clearable>
              </el-input>
              <span v-show="doubleclick!=scope.row.line">{{scope.row.address}}</span>
            </template>
          </el-table-column>
          <el-table-column label="日期1" width="170" sortable align="center">
            <template slot-scope="scope">
              <!-- <el-date-picker v-show="doubleclick==scope.row.line" v-model="scope.row.date" format="yyyy-MM-dd" align="center" type="date" placeholder="选择日期" size="mini" style="width: 58%;">
              </el-date-picker> -->
              <span>{{DateFormats(scope.row.date)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="年龄" prop="age" width="70" align="center"></el-table-column>
          <el-table-column label="数值" prop="num" width="120px" align="right">
            <template slot-scope="scope">
              <el-input v-show="doubleclick==scope.row.line" type="Number" placeholder="请输入内容" v-model.number="scope.row.num" size="mini" clearable>
              </el-input>
              <span v-show="doubleclick!=scope.row.line">{{scope.row.num}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="137px" align="center" fixed="right">
            <template slot-scope="scope">
              <!-- slot-scope="scope" 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据-->
              <el-button size="mini" plain type="primary" @click="HandleEdit(scope.$index, scope.row)" style="margin: 4px;">详情</el-button>
              <el-popover trigger="click" placement="top" width="160" clearable>
                <p>是否确认删除</p>
                <div align="center">
                  <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="DeleteData(scope.$index, tableData)"></el-button>
                </div>
                <!-- slot="reference" 触发 Popover 的元素,使用 slot="reference" 的具名插槽 -->
                <el-button size="mini" plain type="danger" slot="reference">删除</el-button>
              </el-popover>

            </template>

          </el-table-column>

        </el-table>
        <div class="block" align="right">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "invoice-table",
  props: {},
  data() {
    return {
      search: "",
      doubleclick: null, // 记录当前编辑行序号
      deleteTableData: [], // 记录所有标记删除的数据 暂无用
      selectList: [], // 记录本次批量选择的数据
      tableData: [], // datable的数据
      loading: false, // 加载是否转圈圈
      currentPage: 1, // 当前页码
      value: [],
      options: [],
      props: {
        emitPath: false, //若设置 false，则只返回该节点的值
        multiple: false, //多选模式
        expandTrigger: "hover", //定义展开子级菜单的触发方式。
        checkStrictly: true, //父子节点取消选中关联，从而达到选择任意一级选项的目的
      },
    };
  },
  mounted() {
    this.loading = true;
    setTimeout(() => {
      this.initdata();
      this.loading = false;
    }, 100);
  },
  watch: {
    // search(val) {
    //   this.tableData = this.tableData.filter(
    //     (data) => !val || data.name.toLowerCase().includes(val.toLowerCase())
    //   );
    // },
  },
  computed: {
    tableDataSearch() {
      return this.tableData.filter(
        (data) =>
          !this.search ||
          data.name.toLowerCase().includes(this.search.toLowerCase())
      );
    },
    // 动态样式，利用必报解决不能传参的问题
    styleObject() {
      return function (row) {
        return {
          color: row.true ? "red" : "",
        };
      };
    },
  },
  methods: {
    // datable初始化数据
    initdata() {
      this.options = [
        {
          value: "zhinan",
          label: "指南",
          children: [
            {
              value: "shejiyuanze",
              label: "设计原则",
              children: [
                {
                  value: "yizhi",
                  label: "一致",
                },
                {
                  value: "fankui",
                  label: "反馈",
                },
                {
                  value: "xiaolv",
                  label: "效率",
                },
                {
                  value: "kekong",
                  label: "可控",
                },
              ],
            },
            {
              value: "daohang",
              label: "导航",
              children: [
                {
                  value: "cexiangdaohang",
                  label: "侧向导航",
                },
                {
                  value: "dingbudaohang",
                  label: "顶部导航",
                },
              ],
            },
          ],
        },
        {
          value: "zujian",
          label: "组件",
          children: [
            {
              value: "basic",
              label: "Basic",
              children: [
                {
                  value: "layout",
                  label: "Layout 布局",
                },
                {
                  value: "color",
                  label: "Color 色彩",
                },
                {
                  value: "typography",
                  label: "Typography 字体",
                },
                {
                  value: "icon",
                  label: "Icon 图标",
                },
                {
                  value: "button",
                  label: "Button 按钮",
                },
              ],
            },
            {
              value: "form",
              label: "Form",
              children: [
                {
                  value: "radio",
                  label: "Radio 单选框",
                },
                {
                  value: "checkbox",
                  label: "Checkbox 多选框",
                },
                {
                  value: "input",
                  label: "Input 输入框",
                },
                {
                  value: "input-number",
                  label: "InputNumber 计数器",
                },
                {
                  value: "select",
                  label: "Select 选择器",
                },
                {
                  value: "cascader",
                  label: "Cascader 级联选择器",
                },
                {
                  value: "switch",
                  label: "Switch 开关",
                },
                {
                  value: "slider",
                  label: "Slider 滑块",
                },
                {
                  value: "time-picker",
                  label: "TimePicker 时间选择器",
                },
                {
                  value: "date-picker",
                  label: "DatePicker 日期选择器",
                },
                {
                  value: "datetime-picker",
                  label: "DateTimePicker 日期时间选择器",
                },
                {
                  value: "upload",
                  label: "Upload 上传",
                },
                {
                  value: "rate",
                  label: "Rate 评分",
                },
                {
                  value: "form",
                  label: "Form 表单",
                },
              ],
            },
            {
              value: "data",
              label: "Data",
              children: [
                {
                  value: "table",
                  label: "Table 表格",
                },
                {
                  value: "tag",
                  label: "Tag 标签",
                },
                {
                  value: "progress",
                  label: "Progress 进度条",
                },
                {
                  value: "tree",
                  label: "Tree 树形控件",
                },
                {
                  value: "pagination",
                  label: "Pagination 分页",
                },
                {
                  value: "badge",
                  label: "Badge 标记",
                },
              ],
            },
            {
              value: "notice",
              label: "Notice",
              children: [
                {
                  value: "alert",
                  label: "Alert 警告",
                },
                {
                  value: "loading",
                  label: "Loading 加载",
                },
                {
                  value: "message",
                  label: "Message 消息提示",
                },
                {
                  value: "message-box",
                  label: "MessageBox 弹框",
                },
                {
                  value: "notification",
                  label: "Notification 通知",
                },
              ],
            },
            {
              value: "navigation",
              label: "Navigation",
              children: [
                {
                  value: "menu",
                  label: "NavMenu 导航菜单",
                },
                {
                  value: "tabs",
                  label: "Tabs 标签页",
                },
                {
                  value: "breadcrumb",
                  label: "Breadcrumb 面包屑",
                },
                {
                  value: "dropdown",
                  label: "Dropdown 下拉菜单",
                },
                {
                  value: "steps",
                  label: "Steps 步骤条",
                },
              ],
            },
            {
              value: "others",
              label: "Others",
              children: [
                {
                  value: "dialog",
                  label: "Dialog 对话框",
                },
                {
                  value: "tooltip",
                  label: "Tooltip 文字提示",
                },
                {
                  value: "popover",
                  label: "Popover 弹出框",
                },
                {
                  value: "card",
                  label: "Card 卡片",
                },
                {
                  value: "carousel",
                  label: "Carousel 走马灯",
                },
                {
                  value: "collapse",
                  label: "Collapse 折叠面板",
                },
              ],
            },
          ],
        },
        {
          value: "ziyuan",
          label: "资源",
          children: [
            {
              value: "axure",
              label: "Axure Components",
            },
            {
              value: "sketch",
              label: "Sketch Templates",
            },
            {
              value: "jiaohu",
              label: "组件交互文档",
            },
          ],
        },
      ];
      this.tableData = [
        {
          line: 1,
          date: "2022-03-31T17:13:55.000+08:00",
          name: "赫敏",
          address: "上海市普陀区金沙江路 1518 弄",
          age: 23,
          num: 500,
          str1: null,
          str2: null,
          str2laber: null,
          str2dis: false,
          str3: null,
          str3laber: null,
          str3dis: false,
          str4: null,
        },
        {
          line: 2,
          date: "2016-05-04",
          name: "皮卡丘",
          address: "上海市普陀区金沙江路 1517 弄",
          age: 42,
          num: 70000,
          str1: null,
          str2: 20,
          str2laber: "我的貂蝉在哪里",
          str2dis: true,
          str3: null,
          str3laber: null,
          str3dis: false,
          str4: null,
        },
        {
          line: 3,
          date: "2016-05-01",
          name: "钢铁侠",
          address: "上海市普陀区金沙江路 1519 弄",
          age: 37,
          num: 900000,
          str1: null,
          str2: 30,
          str2laber: "夜晚徘徊的可怜家伙,能够收获的只有炮火",
          str2dis: false,
          str3: null,
          str3laber: null,
          str3dis: true,
          str4: null,
        },
        {
          line: 4,
          date: "2016-05-03",
          name: "dobby",
          address: "上海市普陀区金沙江路 1516 弄",
          age: 24,
          num: 7000,
          str1: null,
          str2: null,
          str2laber: null,
          str2dis: true,
          str3: 40,
          str3laber: "东京",
          str3dis: true,
          str4: null,
        },
        {
          line: 5,
          date: "2016-05-03",
          name: "拉姆",
          address: "上海市普陀区金沙江路 1516 弄",
          age: 17,
          num: 130,
          str1: null,
          str2: 90,
          str2laber: "我的安琪拉",
          str2dis: true,
          str3: null,
          str3laber: null,
          str3dis: false,
          str4: null,
        },
        {
          line: 6,
          date: "2016-05-03",
          name: "艾米利亚",
          address: "上海市普陀区金沙江路 1516 弄",
          age: 18,
          num: 200,
          str1: null,
          str2: null,
          str2laber: null,
          str2dis: false,
          str3: 60,
          str3laber: "长沙",
          str3dis: false,
          str4: null,
        },
        {
          line: 7,
          date: "2016-05-03",
          name: "蕾姆",
          address:
            "上海市普陀区金沙江路 1516 弄上海市普陀区金沙江路 1516 弄上海市普陀区金沙江路 1516 弄上海市普陀区金沙江路 1516 弄",
          age: 16,
          num: 120,
          str1: null,
          str2: null,
          str2laber: null,
          str2dis: true,
          str3: 70,
          str3laber: "武汉",
          str3dis: true,
          str4: null,
        },
        {
          line: 8,
          date: "2016-06-13",
          name: "宫水三叶",
          address: "上海市青浦区区汇金路 33 号",
          age: 16,
          num: 120,
          str1: null,
          str2: null,
          str2laber: null,
          str2dis: false,
          str3: null,
          str3laber: null,
          str3dis: false,
          str4: null,
        },
      ];
    },
    // 级联选择器改变事件
    handleChange(value) {
      console.log(value);
    },
    // 选中table行的数据
    SelectFun(val) {
      this.selectList = val;
    },
    // 表头的点击事件
    HeaderClick(column, event) {
      // this.$message("成功表头触发事件");
      this.doubleclick = null;
    },
    // 行的双击事件 / 注意:双击事件会触发两次行的单击事件
    RowDblclick(row, column, event) {
      // this.$message("成功双击触发事件");
      this.doubleclick = row.line;
    },
    // 行的单击事件
    RowClick(row, column, event) {
      // this.$message("成功单击触发事件");
      if (this.doubleclick != row.line) {
        this.doubleclick = null;
      }
    },
    // 行编辑按钮
    HandleEdit: function (index, row) {
      //this.$message((index + 1) + '行,你点击了编辑');
      this.doubleclick = row.line;
    },
    // 确认删除按钮[单条数据]
    DeleteData: function (index, rows) {
      //this.deleteTableData.push(rows[index]);
      this.tableData.splice(index, 1);
      this.lineFun(); // 重新计算行索引
    },
    // 表格外的删除按钮[删除多条数据]
    DeleteTableDataFun: function () {
      if (this.selectList.length == 0) {
        this.$message({
          message: "请选择要删除的行",
          type: "warning",
          showClose: true,
        });
      } else {
        var selectList = this.selectList;
        var tableData = this.tableData;
        var deleteTableData = this.deleteTableData;
        this.$confirm("确定要删除选中行数据吗?", "批量删除", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            for (var i in selectList) {
              for (var j in tableData) {
                if (selectList[i].line == tableData[j].line) {
                  deleteTableData.push(tableData[j]);
                  tableData.splice(j, 1);
                }
              }
            }
            this.lineFun(); // 重新计算行索引
          })
          .catch(function (e) {
            console.log(e.message);
          });
        if (tableData) {
          this.tableData = tableData;
          this.deleteTableData = deleteTableData;
        }
      }
    },
    // 删除完成后需要重新计算行的索引字段line
    lineFun: function () {
      for (var i = 0; i < this.tableData.length; i++) {
        this.tableData[i].line = i + 1;
      }
    },
    // 添加一行
    AddRow: function () {
      var data = {
        line: this.tableData.length + 1,
        date: null,
        name: null,
        address: null,
        age: null,
        num: null,
        str1: null,
        str2: null,
        str2laber: null,
        str3: null,
        str4: null,
      };
      this.tableData.push(data);
      this.doubleclick = this.tableData.length;
    },
    // 保存
    SaveData: function () {
      this.$message({
        showClose: true,
        message: JSON.stringify(this.tableData),
        type: "success",
      });
    },
    // 弹出框点击空白不让关闭事件 暂无用
    HandleClose: function () {
      return false;
    },
    handleSizeChange: function (val) {
      console.log("每页 ${val} 条");
    },
    handleCurrentChange: function (val) {
      console.log("当前页: ${val}");
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = sums[index].toFixed(2); // 保留两位小数，解决小数合计列
        } else {
          sums[index] = "/";
        }
      });

      return sums;
    },
    // 日期框的日期格式转换
    DateFormats: function (date) {
      date = new Date(date);
      if (date != null) {
        var ss = typeof date;
        if (ss == "string") {
          return date;
        }
        var fmt = "yyyy-MM-dd";
        var o = {
          "M+": date.getMonth() + 1, //月份
          "d+": date.getDate(), //日
          "h+": date.getHours(), //小时
          "m+": date.getMinutes(), //分
          "s+": date.getSeconds(), //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        for (var k in o) {
          if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
          }
        }
        return fmt;
      }
    },
    // 验证字符串是否是数字
    checkNumber(val) {
      let reg = /^\d+(\.\d{1,2})?$/;
      if (reg.test(val)) {
        return true;
      }
      return false;
    },
  },
};
</script>

<style scoped>
</style>
